package cn.tedu.charging.device.warm;

import cn.tedu.charging.common.pojo.po.ChargingStationPO;
import cn.tedu.charging.device.dao.repository.StationRepository;
import com.alibaba.nacos.common.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class RedisWarmUp implements ApplicationRunner {
    @Autowired
    private StationRepository stationRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.debug("即将执行缓存预热");
        List<ChargingStationPO> pos=getAllStations();
        if (CollectionUtils.isNotEmpty(pos)){
            log.debug("缓存源数据非空，预热缓存执行");
            saveStationCache(pos);
        }
    }

    private void saveStationCache(List<ChargingStationPO> pos) {
        for (ChargingStationPO po : pos) {
            saveGeoCache(po);
            saveStringCache(po);
        }
        /*List results = redisTemplate.executePipelined((RedisCallback<?>) connection -> {
            for (ChargingStationPO po : pos) {
                saveGeoCache(po);
                saveStringCache(po);
            }
            return null;
        });*/
    }

    private void saveStringCache(ChargingStationPO po) {
        //TODO 前缀也应该使用常量
        String stationKey="station:cache:"+po.getId();
        redisTemplate.opsForValue().set(stationKey,po);
    }

    private void saveGeoCache(ChargingStationPO po) {
        GeoOperations geoOps=redisTemplate.opsForGeo();
        //TODO beijing_stations替换成常量
        geoOps.add("beijing_stations",
                new Point(po.getStationLng().doubleValue(),po.getStationLat().doubleValue()),
                po.getId());
    }

    private List<ChargingStationPO> getAllStations() {
        return stationRepository.findAll();
    }
}
